<?php

namespace app\admin\controller\share;

use addons\shopro\model\Order;
use app\admin\model\share\Reward as ShareReward;
use app\common\controller\Backend;
use \app\admin\model\share\ShareUser;
use think\Db;

/**
 * 推广收益记录
 *
 * @icon fa fa-circle-o
 */
class Reward extends Backend
{

    /**
     * Reward模型对象
     * @var \app\admin\model\share\Reward
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\share\Reward;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 统计
     */
    public function statistics()
    {
        //开始时间
        $end_time = date('Y-m-d 00:00:00');
        // 本周周一时间
        $week_time1 = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));

        // 当前时间
        $dq_time = date('Y-m-d H:i:s');
        if ($this->request->isAjax()) {
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            $where = [];
            $week_where = [];
            $userId = isset($filterArr['user_id']) ? $filterArr['user_id'] : '';
            if(!$userId){
                $this->error(__('团队用户ID不能为空'));
            }

            $where['user_id'] = $userId;
            if (isset($filterArr['addtime'])) {
                $timeArr = explode(' - ', $filterArr['addtime']);
                $where['addtime'] = ['between', [strtotime($timeArr[0]), strtotime($timeArr[1])]];
                $tempArr = $this->get_week($timeArr[0]);
                $week_where['addtime'] = ['between', [strtotime($tempArr[0]), strtotime($tempArr[1])]];
            } else {
                $where['addtime'] = ['between', [strtotime($end_time), strtotime($dq_time)]];
                $tempArr = $this->get_week($end_time);
                $week_where['addtime'] = ['between', [strtotime($tempArr[0]), strtotime($tempArr[1])]];
            }


            /*$d_reward5 = $this->model->where($where)->where(['type' => 5])->sum('money');
            $d_reward4 = $this->model->where($where)->where(['type' => 4])->sum('money');
            $d_reward2 = $this->model->where($where)->where(['type' => 2])->sum('money');
            $d_reward1 = $this->model->where($where)->where(['type' => 1])->sum('money');
            $d_reward3 = $this->model->where($week_where)->where(['type' => 3])->sum('money');
            $ShareUser1 = (new ShareUser())->where(['is_delete' => 0, 'role' => 1])->count();
            $ShareUser2 = (new ShareUser())->where(['is_delete' => 0, 'role' => 2])->count();
            $ShareUser3 = (new ShareUser())->where(['is_delete' => 0, 'role' => 3])->count();
            $ShareUser4 = (new ShareUser())->where(['is_delete' => 0, 'role' => 4])->count();
            $ShareUser5 = (new ShareUser())->where(['is_delete' => 0, 'role' => 5])->count();
            $ShareUser6 = (new ShareUser())->where(['is_delete' => 0, 'role' => 6])->count();
            $ShareUser7 = (new ShareUser())->where(['is_delete' => 0, 'role' => 7])->count();*/

            $dataArr = $this->getStatistics($userId);
            $dataArr = $dataArr['list'];
            $data = array();
            $data[] = array('title' => '推广员日总创收', 'money' => $dataArr['tgy_day_income']['money']);
            $data[] = array('title' => '代言人日总创收', 'money' => $dataArr['dyr_day_income']['money']);
            $data[] = array('title' => '一星网店主日总创收', 'money' => $dataArr['yxwd_day_income']['money']);
            $data[] = array('title' => '一星网店主周总创收', 'money' => $dataArr['yxwd_week_income']['money']);
            $data[] = array('title' => '二星网店主日总创收', 'money' => $dataArr['exwd_day_income']['money']);
            $data[] = array('title' => '推广员总人数', 'money' => $dataArr['tgy_user_num']['count']);
            $data[] = array('title' => '代言人总人数', 'money' => $dataArr['dyr_user_num']['count']);
            $data[] = array('title' => '一星网店主总人数', 'money' => $dataArr['yxwd_user_num']['count']);
            $data[] = array('title' => '二星网店主总人数', 'money' => $dataArr['exwd_user_num']['count']);
            $data[] = array('title' => '银牌经销商总人数', 'money' => $dataArr['yp_user_num']['count']);
            $data[] = array('title' => '金牌经销商总人数', 'money' => $dataArr['jp_user_num']['count']);
            $data[] = array('title' => '钻石经销商总人数', 'money' => $dataArr['zs_user_num']['count']);

            $result = array("total" => 12, "rows" => $data);
            return json($result);
        }
        return $this->view->fetch();
    }

    private function get_week($sdefaultDate)
    {
        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期  
        $first = 1;
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6  
        $w = date('w', strtotime($sdefaultDate));
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天  
        $week_start = date('Y-m-d', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
        //本周结束日期  
        $week_end = date('Y-m-d', strtotime("$week_start +6 days"));
        return array($week_start, $week_end);
    }

    /**
     * 统计
     */
    //  public function statistics()
    //  {
    //     $data = array();

    //      //开始时间
    //      $start_time = date("Y-m-d 00:00:00", strtotime("-1 day"));
    //      //结束时间
    //      $end_time = date('Y-m-d 00:00:00');

    //      $data['reward5'] = $this->model->where('addtime', 'between time', [$start_time, $end_time])->where(['type'=>5,'status'=>0])->sum('money');
    //      $data['reward4'] = $this->model->where('addtime', 'between time', [$start_time, $end_time])->where(['type'=>4,'status'=>0])->sum('money');
    //      $data['reward2'] = $this->model->where('addtime', 'between time', [$start_time, $end_time])->where(['type'=>2,'status'=>0])->sum('money');
    //      $data['reward1'] = $this->model->where('addtime', 'between time', [$start_time, $end_time])->where(['type'=>1,'status'=>0])->sum('money');
    //      // 本周周一时间
    //      $week_time1 = date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y")));
    //      // 上周一时间
    //      $week_time = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')));
    //      $data['reward3'] =$this->model->where('addtime', 'between time', [$week_time, $week_time1])->where(['type'=>3,'status'=>0])->sum('money');

    //      // 当前时间
    //      $dq_time = date('Y-m-d H:i:s');
    //      $data['d_reward5'] = $this->model->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>5,'status'=>0])->sum('money');
    //      $data['d_reward4'] = $this->model->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>4,'status'=>0])->sum('money');
    //      $data['d_reward2'] = $this->model->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>2,'status'=>0])->sum('money');
    //      $data['d_reward1'] = $this->model->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>1,'status'=>0])->sum('money');
    //      $data['d_reward3'] =$this->model->where('addtime', 'between time', [$week_time1, $dq_time])->where(['type'=>3,'status'=>0])->sum('money');

    //     $this->view->assign("data", $data);
    //     return $this->view->fetch();
    //  }

    public function getStatistics($userId)
    {

        $user =(new ShareUser())->get(['user_id'=>$userId]); // 分销用户
        //$puser =(new ShareUser())->get(['user_id'=>$user->parent_id]);

        $teamlist = \db('share_user')->where(['is_sep_income'=>1])->select();

        $teamUserAll = $this->getSepTeamUser($userId);
        $teamUidArr = array_unique($teamUserAll['team_user']);

        $userWhere = ['user_id'=>0];
        if(in_array($userId, $teamUidArr)){
            $userWhere = ['user_id'=>['IN', $teamUidArr]];
        }


        $data = array();
        //开始时间
        $end_time = date('Y-m-d 00:00:00');
        // 当前时间
        $dq_time = date('Y-m-d H:i:s');
        // 本周周一时间
        $week_time1 = date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y")));
        $sdefaultDate = date("Y-m-d");
        $first=1;
        $w=date('w',strtotime($sdefaultDate));
        $week_start=date('Y-m-d H:i:s',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
        $data['d_reward5'] = (new \app\admin\model\share\Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>5])->where($userWhere)->sum('money');

        $data['d_reward4'] = (new \app\admin\model\share\Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>4])->where($userWhere)->sum('money');
        //$data['today_reward3'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>3])->where($userWhere)->sum('money');
        //$data['d_reward3'] = (new Reward())->where('addtime', 'between time', [$week_time1, $dq_time])->where(['type'=>3])->where($userWhere)->sum('money');
        $data['d_reward3'] = (new \app\admin\model\share\Reward())->where('addtime', 'between time', [$week_start, $dq_time])->where(['type'=>3])->where($userWhere)->sum('money');
        $data['d_reward2'] = (new \app\admin\model\share\Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>2])->where($userWhere)->sum('money');
        $data['d_reward1'] = (new \app\admin\model\share\Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type'=>1])->where($userWhere)->sum('money');
        //开始时间
        $yest_time = date("Y-m-d", strtotime("-1 day"));
        // 上周一时间
        //$week_time = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y')));
        $week_time = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y')));
        //echo $week_time;
        $ShareReward5 = (new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>5])->where($userWhere)->sum('money');
        $ShareReward4 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>4])->where($userWhere)->sum('money');
        //$yestodayShareReward3 =(new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>3])->where($userWhere)->sum('money');
        //$ShareReward3 =(new ShareReward())->where('addtime', 'between time', [$week_time, $week_time1])->where(['type'=>3])->where($userWhere)->sum('money');
        $ShareReward3 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$week_time, $week_start])->where(['type'=>3])->where($userWhere)->sum('money');
        $ShareReward2 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>2])->where($userWhere)->sum('money');
        $ShareReward1 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>1])->where($userWhere)->sum('money');

        //昨日我的广告收益总额
        $uids = '';
        $order_list = (new Order())
            ->where('paytime', 'between time', [$yest_time, $end_time])
            ->where('status','in','1,2')
            ->where(['user_id'=>$userId])
            ->select();
        foreach ($order_list as $k=>$v){
            $uids .= ','.$v['id'];
        }
        $uids = trim($uids,',');
        $UserShareReward5 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>5])->where('order_id','in',$uids)->sum('money');
        $UserShareReward4 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>4])->where('order_id','in',$uids)->sum('money');
        //$yestodayShareReward3 =(new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>3])->where($userWhere)->sum('money');
        //$UserShareReward3 =(new ShareReward())->where('addtime', 'between time', [$week_time, $week_time1])->where(['type'=>3])->where('order_id','in',$uids)->sum('money');
        $UserShareReward3 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$week_time, $week_start])->where(['type'=>3])->where('order_id','in',$uids)->sum('money');
        $UserShareReward2 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>2])->where('order_id','in',$uids)->sum('money');
        $UserShareReward1 =(new \app\admin\model\share\Reward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type'=>1])->where('order_id','in',$uids)->sum('money');

        if($userWhere['user_id'] == 0){
            $userWhere = [];
        }
        $ShareUser1 =(new ShareUser())->where(['is_delete'=>0, 'role'=>1])->where($userWhere)->count();
        $ShareUser2 =(new ShareUser())->where(['is_delete'=>0, 'role'=>2])->where($userWhere)->count();
        $ShareUser3 =(new ShareUser())->where(['is_delete'=>0, 'role'=>3])->where($userWhere)->count();
        $ShareUser4 =(new ShareUser())->where(['is_delete'=>0, 'role'=>4])->where($userWhere)->count();

        $money1 = empty($ShareUser1) ? 0: bcdiv($data['d_reward1'],$ShareUser1,2);
        $t_money1 =  ($user['role'] != 1) ? 0 : $money1;
        $money2 =  empty($ShareUser2) ? 0: bcdiv($data['d_reward2'],$ShareUser2,2);
        $t_money2 = ($user['role'] != 2) ? 0 : $money2;
        $money3 =  empty($ShareUser3) ? 0: bcdiv($data['d_reward3'],$ShareUser3,2);
        $t_money3 = ($user['role'] != 3) ? 0 : $money3;
        $money4 = empty($ShareUser3) ? 0: bcdiv($data['d_reward4'],$ShareUser3,2);
        $t_money4 = ($user['role'] != 3) ? 0 : $money4;
        $money5 = empty($ShareUser4) ? 0: bcdiv($data['d_reward5'],$ShareUser4,2);
        $t_money5 = ($user['role'] != 4) ? 0 :  $money5;

        $shareUser5 = \db('share_user')->where(['role'=>5, 'is_sep_income'=>1])->count();
        $shareUser6 = \db('share_user')->where(['role'=>6, 'is_sep_income'=>1])->count();
        $shareUser7 = \db('share_user')->where(['role'=>7, 'is_sep_income'=>1])->count();

        $temp_arr = array();
        $temp_arr['tgy_day_income'] = array('role' => 1, 'name' => '推广员日创收', 'money' =>  round($data['d_reward1'],2),'my_money'=>round($money1,2),'yest_money'=>round($ShareReward1,2),'yest_user_money'=>round($UserShareReward1,2));
        $temp_arr['dyr_day_income'] = array('role' => 2, 'name' => '代言人日创收', 'money' =>  round($data['d_reward2'],2),'my_money'=>round($money2,2),'yest_money'=>round($ShareReward2,2),'yest_user_money'=>round($UserShareReward2,2));
        $temp_arr['yxwd_day_income'] = array('role' => 3, 'name' => '一星网店主日创收', 'money' =>  round($data['d_reward4'],2),'my_money'=>round($money4,2),'yest_money'=>round($ShareReward4,2),'yest_user_money'=>round($UserShareReward4,2));
        $temp_arr['yxwd_week_income'] = array('role' => 3, 'name' => '一星网店主周创收', 'money' =>  round($data['d_reward3'],2),'my_money'=>round($money3,2),'yest_money'=>round($ShareReward3,2),'yest_user_money'=>round($UserShareReward3,2));
        $temp_arr['exwd_day_income'] = array('role' => 4, 'name' => '二星网店主日创收', 'money' =>  round($data['d_reward5'],2),'my_money'=>round($money5,2),'yest_money'=>round($ShareReward5,2),'yest_user_money'=>round($UserShareReward5,2));

        $temp_arr['tgy_user_num'] = array('role' => 1, 'name' => '推广员总人数', 'count'=>$ShareUser1);
        $temp_arr['dyr_user_num'] = array('role' => 2, 'name' => '代言人总人数', 'count'=>$ShareUser2);
        $temp_arr['yxwd_user_num'] = array('role' => 3, 'name' => '一星网店主总人数', 'count'=>$ShareUser3);
        $temp_arr['exwd_user_num'] = array('role' => 4, 'name' => '二星网店主总人数', 'count'=>$ShareUser4);
        $temp_arr['yp_user_num'] = array('role' => 5, 'name' => '银牌经销商总人数', 'count'=>$shareUser5);
        $temp_arr['jp_user_num'] = array('role' => 6, 'name' => '金牌经销商总人数', 'count'=>$shareUser6);
        $temp_arr['zs_user_num'] = array('role' => 7, 'name' => '钻石经销商总人数', 'count'=>$shareUser7);

        //$total_money = $data['d_reward1'] + $data['d_reward2'] + $data['d_reward3'] + $data['d_reward4'] + $data['d_reward5'];
        //$total_yest_money = $ShareReward1 + $ShareReward2 + $ShareReward3 + $ShareReward4 + $ShareReward5;
        $total_money = $data['d_reward1'] + $data['d_reward2'] + $data['d_reward4'] + $data['d_reward5'];
        $total_yest_money = $ShareReward1 + $ShareReward2  + $ShareReward4 + $ShareReward5;
        $total_yest_user_money = $UserShareReward1 + $UserShareReward2 + $UserShareReward3 + $UserShareReward4 + $UserShareReward5;
        $my_money = 0;
        switch ($user['role']) {
            case 1:
                $my_money = $t_money1;
                break;
            case 2:
                $my_money = $t_money2;
                break;
            case 3:
                $my_money = bcadd($t_money3,$t_money4);
                break;
            case 4:
                $my_money = $t_money5;
                break;
        }
        $one =  array('money' =>  round($data['d_reward3'],2),'my_money'=>round($money3,2),'yest_money'=>round($ShareReward3,2),'yest_user_money'=>round($UserShareReward3,2));
        return array('one' => $one,'list' => $temp_arr,'total_list'=>array('yest_money'=>round($total_yest_money,2),'yest_user_money'=>round($total_yest_user_money,2),'money'=>round($total_money,2),'my_money'=>round($my_money,2)));
    }

    private function getSepTeamUser($userId){
        //$user =(new ShareUser())->get(['user_id'=>$this->user_id]); // 分销用户
        //$puser =(new ShareUser())->get(['user_id'=>$user->parent_id]);

        $teamlist = Db::table('share_user')->where(['is_sep_income'=>1])->select();
        $teamUidArr = [];
        $noteamUidArr = [];
        if(!empty($teamlist)){
            foreach($teamlist as $val){
                $puserlist = Db::table('share_user')->where(['role_url'=>['like', "%".$val['user_id']."%"]])->order('id DESC')->select();
                $userIdsStr = '';
                foreach($puserlist as $vv){
                    $userIdsStr = $userIdsStr.$val['role_url'].'/'.$vv['user_id'];
                }

//                foreach($puserlist as $vl) {
                $userArray = explode('/', $userIdsStr);
                $teamArray = array_filter($userArray);
                $teamArray = array_merge($teamArray, [$val['user_id']]);
                //$isSepIncome = Db::table('share_user')->where(['user_id'=>['IN', $teamArray], 'is_sep_income'=>1])->count();
                if(in_array($userId, $teamArray)) {
                    foreach ($teamArray as $k => $uid) {
                        if ($uid >= $val['user_id']) {
                            $teamUidArr[$k] = $uid;
                        } else {
                            $noteamUidArr[$k] = $uid;
                        }
                    }
                    break;
                }
//                }
            }
        }
        $teamUidArr = array_unique($teamUidArr);
        $noteamUidArr = array_unique($noteamUidArr);
        return ['team_user'=>$teamUidArr, 'noteam_user'=>$noteamUidArr];
    }
}
